package com.fh.controller.role;

import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.entity.system.User;
import com.fh.service.attachment.AttachmentService;
import com.fh.service.building.RecordService;
import com.fh.service.business.BusinessService;
import com.fh.service.role.ShsRoleService;
import com.fh.service.system.role.RoleService;
import com.fh.service.system.user.UserService;
import com.fh.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.fh.controller.system.tools.GetDatalayui.getLData;
import static com.fh.controller.system.tools.GetDatalayui.getPData;


/**
 * 类名称：ShsRoleController
 * 创建人：FH
 * 创建时间：2017-09-19
 */
@Controller
@RequestMapping(value = "/shsRole")
public class ShsRoleController extends BaseController {

    @Resource(name = "shsRoleService")
    private ShsRoleService roleService;
    @Resource(name = "userService")
    private UserService userService;
    @Resource(name = "recordService")
    private RecordService recordService;

    /**
     * 角色列表(json)
     */
    @RequestMapping(value = "/json")
    @ResponseBody
    public Object json(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            //测试分页 导出为layui的json数据
            pd = this.getPageData();
            pd.put("USER_ID", user.getUSER_ID());
            getPData(page, pd);//必填 2参
            varList = roleService.list(page);    //列出role列表
            datalayui = getLData(page, varList);//必填 2参
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public PageData save() {
        logBefore(logger, "新增Role");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {

            // 保存角色信息
            pd.put("ID", this.get32UUID());    //主键
            pd.put("IS_DEL", 0); //是否删除
            pd.put("CREATE_ID", user.getUSER_ID()); //创建人
            pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            roleService.save(pd);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","新增角色");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public PageData edit() {
        logBefore(logger, "修改Role");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {

            roleService.edit(pd);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","修改角色");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 通过ID获取详情信息
     */
    @RequestMapping(value = "/info")
    @ResponseBody
    public PageData info() {
        logBefore(logger, "Role详情");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            PageData data = roleService.findById(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 角色列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public PageData list() {
        logBefore(logger, "Role列表");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            pd.put("USER_ID", user.getUSER_ID());
            List<PageData> list = roleService.listAll(pd);
            res.put("data", list);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 权限列表
     */
    @RequestMapping(value = "/authList")
    @ResponseBody
    public PageData authList() {
        logBefore(logger, "Auth列表");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            List<PageData> list = roleService.authList(pd);
            res.put("data", list);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 获取当前登录用户具有哪些权限
     */
    @RequestMapping(value = "/auth")
    @ResponseBody
    public PageData auth() {
        logBefore(logger, "获取当前登录用户具有哪些权限");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            /*String token = user.getTOKEN();
            if (Tools.isEmpty(token)) {
                res.put("data", "");
                res.put("errcode", "9");
                res.put("errmsg", "登录超时或认证失败");
                return res;
            }
            PageData pdIn = new PageData();
            pdIn.put("TOKEN", token);
            PageData pdUser = userService.findByToken(pdIn);
            if (pdUser == null) {
                res.put("data", "");
                res.put("errcode", "9");
                res.put("errmsg", "登录超时或认证失败");
                return res;
            }*/
            pd.put("USER_ID", user.getUSER_ID());
            PageData data = roleService.authListByLoginUser(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 获取用户具有哪些数据权限
     */
    @RequestMapping(value = "/dataAuth")
    @ResponseBody
    public PageData dataAuth() {
        logBefore(logger, "获取用户具有哪些数据权限");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {

            List<PageData> data = roleService.dataAuthListByUserId(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 保存用户数据权限
     */
    @RequestMapping(value = "/saveDataAuth")
    @ResponseBody
    public PageData saveDataAuth() {
        logBefore(logger, "保存用户数据权限");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {

            String type = pd.getString("TYPE");
            if (type.equals("0")) {         // 新增数据权限
                pd.put("ID", this.get32UUID());
                roleService.delDataAuth(pd);
                roleService.saveDataAuth(pd);
            } else if (type.equals("1")) {  // 删除数据权限
                roleService.delDataAuth(pd);
            }
            res.put("data", null);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 审核等级列表
     */
    @RequestMapping(value = "/shenHeAuth")
    @ResponseBody
    public PageData shenHeAuth() {
        logBefore(logger, "shenHeAuth列表");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            pd.put("USER_ID", user.getUSER_ID());
            PageData data = roleService.shenHeAuth(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 保存审核等级
     */
    @RequestMapping(value = "/editShenHeAuth")
    @ResponseBody
    public PageData editShenHeAuth() {
        logBefore(logger, "editShenHeAuth");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            pd.put("COMPANY_ID", user.getCOMPANY_ID());
            roleService.editShenHeAuth(pd);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /* ===============================权限================================== */
    public Map<String, String> getHC() {
        Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
        Session session = currentUser.getSession();
        return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
    }
    /* ===============================权限================================== */

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format, true));
    }
}
